<?php
class userModel extends RPHP_Model
{

    //获取用户收藏
    public function getCollectionList($page, $pagesize = 6)
    {
        $sql = "SELECT COUNT(`id`) AS `cnt` FROM {$this->_prefix['primary']}goods_collection WHERE `uid`=" . $this->_user['uid'];
        $cnt = $this->db->getone($sql);
        if ($cnt > 0) {

            $start = ($page - 1) * $pagesize;

            $sql = "SELECT `id`,`goods_id` FROM {$this->_prefix['primary']}goods_collection WHERE  `uid`=" . $this->_user['uid'] . " ORDER BY `create_time` DESC LIMIT " . $start . "," . $pagesize;

            $rs = $this->sql($sql);

            if ($rs) {
                foreach ($rs as $r) {

                    $goods_id[$r['goods_id']] = $r['goods_id'];
                }

                $sql = "SELECT `goods_id`,`goods_name`,`market_price`,`shop_price`,`thumb_docid`,`pic_docid`,`sales_count` FROM {$this->_prefix['primary']}goods_data WHERE `goods_id` IN (" . implode(",", $goods_id) . ") AND `is_on_sale`=1 AND `is_delete`=0";
                $tmp = $this->sql($sql);
                if ($tmp) {
                    foreach ($tmp as $r) {

                        $goods[$r['goods_id']] = $r;
                        if ($r['thumb_docid'] == 0 && $r['pic_docid'] > 0) {
                            $r['thumb_docid'] = $goods[$r['goods_id']]['thumb_docid'] = $r['pic_docid'];
                        }

                        if ($r['thumb_docid'] > 0) {
                            $docids[] = $r['thumb_docid'];
                        }

                        $goods_ids[] = $r['goods_id'];
                    }

                    if ($docids) {
                        $docs = $this->getDocs($docids);
                    }

                    // 获取库存
                    if ($goods_ids) {
                        $sql = "SELECT `goods_id`,`number` FROM {$this->_prefix['primary']}goods_stock WHERE `goods_id` IN (" . implode(",", $goods_ids) . ")";
                        $tmp = $this->sql($sql);
                        if ($tmp) {
                            foreach ($tmp as $r) {
                                $goods_stock[$r['goods_id']] = $r['number'];
                            }
                        }
                    }
                }

                foreach ($rs as $k => $r) {
                    if ($goods[$r['goods_id']]) {
                        $data[] = $goods[$r['goods_id']];

                        $index                        = count($data) - 1;
                        $data[$index]['id']           = $r['id'];
                        $data[$index]['goods_number'] = $goods_stock[$r['goods_id']] > 0 ? $goods_stock[$r['goods_id']] : 0;

                        if ($goods[$r['goods_id']]['thumb_docid'] > 0 && $docs[$goods[$r['goods_id']]['thumb_docid']]) {
                            $data[$index]['thumb_pic'] = $docs[$goods[$r['goods_id']]['thumb_docid']];
                        }
                    }
                }

            }
        }
        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt / $pagesize),
            'count'   => $cnt,
            'data'    => $data,

        );
    }

    //移除单个收藏
    public function removeCollection($id)
    {
        $code = 900;
        $sql  = "DELETE FROM {$this->_prefix['primary']}goods_collection WHERE `id`=" . intval($id) . " AND `uid`=" . $this->_user['uid'];
        $rs   = $this->sql($sql);
        if ($rs > 0) {
            $code = 200;
        }

        return array(
            'code' => $code,
        );
    }

    //获取我的公告

    public function getAdvDetail()
    {
        //通知
        $sql       = "SELECT * FROM {$this->_prefix['primary']}adv WHERE `position` = 6 AND status=1 order by ctime desc";
        $newDetail = $this->db->getrow($sql);
        return $newDetail;

    }
    //获取推荐人信息
    public function getPidMember()
    {
        $pid_info    = array();
        $sql         = "SELECT * FROM {$this->_prefix['primary']}member_account WHERE `uid`=" . $this->_user['uid'];
        $member_info = $this->db->getrow($sql);
        if ($member_info['pid'] > 0) {
            $sql      = "SELECT * FROM {$this->_prefix['primary']}member_account WHERE `uid`=" . $member_info['pid'];
            $pid_info = $this->db->getrow($sql);
            return $pid_info;
        }

    }

    //验证推荐码是否正确
    public function isCode($da)
    {
        $code = 900;
        $msg  = '推荐码不存在';

        $recode = intval($da['code']);
        if ($recode > 0) {
            $sql         = "SELECT `uid` FROM {$this->_prefix['primary']}member_account WHERE `recode`='" . $recode . "' AND `member_level`=1 AND `stat`=1";
            $member_info = $this->db->getrow($sql);
            if ($member_info > 0) {
                $code = 200;
            }
        }

        return array(
            'code' => $code,
            'msg'  => $msg,
        );
    }

    // 获取个人信息
    public function getMyProfile($uid = 0, $getdoc = true, $checkrecode = true)
    {
        $sql  = "SELECT * FROM {$this->_prefix['primary']}member_account WHERE `uid`=" . intval($uid);
        $data = $this->db->getrow($sql);
        if ($data) {

            if ($checkrecode && $data['recode'] == "") {

                $px             = array(1, 2, 3, 5, 6, 7, 9);
                $data['recode'] = $data['uid'] . $px[rand(0, 6)];

                $sql = "UPDATE {$this->_prefix['primary']}member_account SET `recode`='" . $data['recode'] . "' WHERE `uid`=" . $data['uid'];
                $this->sql($sql);
            }

            if ($getdoc) {
                //获取图像
                $member_info['pid'] = '';
                if ($data['headimgurl'] > 0) {
                    $pic                = $this->getPic($data['headimgurl']);
                    $data['headimgurl'] = $pic[0]['img_url'];
                }
            }

            return $data;
        }

    }

    // 获取用户信息
    public function getProfile($uid = 0)
    {
        if ($uid < 1) {
            $uid = $this->_user['uid'];
        }

        $sql  = "SELECT * FROM {$this->_prefix['primary']}member_account WHERE `uid`=" . $uid;
        $data = $this->db->getrow($sql);
        if ($data) {

            $sql            = "SELECT * FROM {$this->_prefix['primary']}member_wechat WHERE `uid`=" . $data['uid'];
            $data['wechat'] = $this->db->getrow($sql);

            return $data;
        }

    }

    public function getPic($docid, $type = false)
    {
        if (is_array($docid)) {
            $where = " WHERE `docid` IN (" . implode(",", array_unique($docid)) . ")";
        } else {
            if (!$type) {
                $where = " WHERE `docid`=" . intval($docid);
            } else {

                $where = " WHERE `docid` IN (" . $docid . ")";
            }

        }

        $sql = "SELECT `docid`,`filename`,`create_time`,imgwh FROM {$this->_prefix['primary']}documents " . $where;
        $rs  = $this->sql($sql);
        if ($rs) {
            foreach ($rs as $k => $r) {
                $doc[$k]['img_url'] = $this->c['doc_host'] . date("Ymd", $r['create_time']) . "/" . date("H", $r['create_time']) . "/" . date("i", $r['create_time']) . "/" . $r['filename'];
                $doc[$k]['imgwh']   = $r['imgwh'];
            }
            return $doc;
        } else {
            return false;
        }

    }

    //用户订单数量统计
    public function getOrderCountByType()
    {
        $count['order_count']       = 0;
        $count['not_pay_count']     = 0;
        $count['send_count']        = 0;
        $count['sended_count']      = 0;
        $count['rebackapply_count'] = 0;
        $sql                        = "SELECT `pay_status`,`order_status`,`shipping_status`,`is_comment` FROM {$this->_prefix['primary']}order_info WHERE `uid`=" . $this->_user['uid'];
        $data                       = $this->sql($sql);
        if ($data) {
            foreach ($data as $r) {
                //待付款
                if ($r['pay_status'] == 0 && $r['order_status'] == 0) {
                    $count['not_pay_count'] += 1;
                }
                //待发货
                elseif ($r['pay_status'] == 2 && $r['order_status'] == 1 && ($r['shipping_status'] == 0 || $r['shipping_status'] == 3 || $r['shipping_status'] == 5)) {

                    $count['send_count'] += 1;
                }
                //待收货
                elseif ($r['pay_status'] == 2 && $r['shipping_status'] == 1) {

                    $count['sended_count'] += 1;
                }
                //退货退款
                elseif ($r['pay_status'] == 3 || $r['pay_status'] == 5 || $r['shipping_status'] == 7 || $r['shipping_status'] == 4) {

                    $count['rebackapply_count'] += 1;
                }
            }

            //全部订单
            $count['order_count'] = count($data);
        }

        return $count;

    }

    //获取用户信息
    public function getMemberInfo()
    {

        $sql = "SELECT * FROM {$this->_prefix['primary']}member_account WHERE  uid=" . $this->_user['uid'] . " limit 1";
        $rs  = $this->db->getrow($sql);

        if ($rs['headimgurl'] > 0) {
            $docs = $this->getDocs($rs['headimgurl']);
            if ($docs[$rs['headimgurl']]) {
                $rs['wechat_headimgurl'] = $docs[$rs['headimgurl']];
            }
        }

        return $rs;

    }

    //保存推荐人id
    public function saveMemberCode($recode)
    {
        $code = 900;
        $msg  = '推荐码不能为空';

        $recode = intval($recode);
        if ($recode) {
            $sql = "SELECT `uid` FROM {$this->_prefix['primary']}member_account WHERE `recode`='" . $recode . "' AND `stat`=1";
            $pid = $this->db->getone($sql);
            if ($pid > 0) {
                $sql   = "UPDATE {$this->_prefix['primary']}member_account SET `pid`=" . $pid . " WHERE `uid`=" . $this->_user['uid'];
                $re_id = $this->sql($sql);
                if ($re_id) {
                    $msg  = '保存成功';
                    $code = 200;
                } else {
                    $msg  = '保存失败，请重试！';
                    $code = 902;
                }
            } else {
                $msg  = '推荐码不存在';
                $code = 901;
            }
        }
        $arr['code'] = $code;
        $arr['msg']  = $msg;
        return $arr;

    }

    // 获取微信用户昵称与头像
    public function getRefreshWechatInfo()
    {
        $setting = $this->getWeixinSetting(true);
        if ($setting['access_token'] != "") {
            $sql    = "SELECT `openid` FROM {$this->_prefix['primary']}member_wechat WHERE `uid`=" . $this->_user['uid'];
            $openid = $this->db->getone($sql);
            if ($openid != "") {
                $url           = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $setting['access_token'] . "&openid=" . $openid . "&lang=zh_CN";
                $user_tmp_data = file_get_contents($url);
                $user          = json_decode($user_tmp_data, true);
                if ($user['nickname'] != "" && $user['headimgurl'] != "") {
                    return array(
                        'nickname'   => str_replace("?", "", $user['nickname']),
                        'headimgurl' => str_replace("/132", "/0", $user['headimgurl']),
                    );
                }

            }
        }

    }

    //转账功能
    public function subTransfer($da)
    {
        $mobile = trim($da['mobile']);
        $number = intval($da['number']);
        $type   = intval($da['type']);
        $cod    = 900;
        $msg    = "转账失败，请重试";
        if ($number > 0) {

            if(strlen($da['mobile'])==11){
                /*  if(preg_match("/^(13|14|15|16|17|18|19)([0-9]{9})$/", $mobile)){

                       return $this->error("手机格式不正确");
                   }*/



                $where = " `mobile`='".$da['mobile']."'";
            }else{

                $where = " `recode`='".$da['mobile']."'";
            }
            //查出转账UID
            $sql = "SELECT `uid`,`realname` FROM {$this->_prefix['primary']}member_account WHERE ".$where;
            $uid = $this->db->getrow($sql);

            if ($uid && $uid['uid'] != $this->_user['uid']) {

                $mymobile = $this->db->getone("SELECT `mobile` FROM {$this->_prefix['primary']}member_account WHERE `uid`=" . $this->_user['uid']);

                $balance     = $this->getBalance();
                $total_money = 0;

                if ($type == 1) {
                    $name        = "硒豆";
                    $event       = 15;
                    $total_money = $balance['money'];
                    $field       = "`money` = `money`-" . $number;

                } elseif ($type == 2) {

                    $name        = "硒米";
                    $total_money = $balance['ximi_money'];
                    $field       = "`ximi_money` = `ximi_money`-" . $number;
                    $event       = 18;

                } elseif ($type == 3) {

                    $name        = "金花";
                    $total_money = $balance['gold_money'];
                    $field       = "`gold_money` = `gold_money`-" . $number;
                    $event       = 23;

                }

                if ($total_money >= $number) {
                    //开启事务
                    $this->db->begin();
                    $commit = false;
                    //扣除
                    $sql  = "UPDATE {$this->_prefix['primary']}finance_balance SET " . $field . ",`last_edit`=" . $_SERVER['REQUEST_TIME'] . ",`update_time`=" . $_SERVER['REQUEST_TIME'] . ",`random_num`=" . rand(100000, 999999) . " WHERE `uid`=" . $this->_user['uid'];
                    $baup = $this->sql($sql);
                    if ($baup > 0) {

                        //保存元宝明细
                        $detail_note = $name . '转出成功，转至手机号' . $da['mobile'];
                        $sql         = "INSERT INTO {$this->_prefix['primary']}finance_detail (`uid`,`event`,`cmoney`,`money`,`create_time`,`note`,`dataid`,`table_name`) VALUES (" . $this->_user['uid'] . "," . $event . "," . $number . "," . ($total_money - $number) . "," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "'," . $balance['uid'] . ",'finance_balance')";
                        $detail_id   = $this->sql($sql);

                        if ($detail_id > 0) {
                            //查出转账人可用
                            $sql     = "SELECT `money`,`money`,`uid` FROM {$this->_prefix['primary']}finance_balance WHERE `uid`=" . $uid['uid'];
                            $balance = $this->db->getrow($sql);

                            $real_money = 0;

                            if ($type == 1) {

                                $event       = 16;
                                $total_money = $balance['money'];
                                $field1      = "`money` = `money`+" . $number;
                                $real_money  = $number;

                            } elseif ($type == 2) {
                                $total_money = $balance['ximi_money'];
                                $event       = 17;
                                $field1      = "`ximi_money` = `ximi_money`+" . $number;
                            } elseif ($type == 3) {
                                $total_money = $balance['gold_money'];
                                $event       = 24;
                                $field1      = "`gold_money` = `gold_money`+" . $number;
                            }

                            //对方增加
                            $sql    = "UPDATE {$this->_prefix['primary']}finance_balance SET " . $field1 . ",`last_edit`=" . $_SERVER['REQUEST_TIME'] . ",`update_time`=" . $_SERVER['REQUEST_TIME'] . ",`random_num`=" . rand(100000, 999999) . " WHERE `uid`=" . $balance['uid'];
                            $badown = $this->sql($sql);
                            if ($badown) {

                                //保存资金明细
                                $detail_note = $name . '转入成功，源自手机号' . $mymobile;
                                $sql         = "INSERT INTO {$this->_prefix['primary']}finance_detail (`uid`,`event`,`cmoney`,`money`,`create_time`,`note`,`dataid`,`table_name`,`real_money`) VALUES (" . $balance['uid'] . "," . $event . "," . $number . "," . ($total_money + $number) . "," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "'," . $balance['uid'] . ",'finance_balance'," . $real_money . ")";
                                $t_id        = $this->sql($sql);

                                if ($t_id) {
                                    $commit = true;

                                } else {

                                    $code = 413;
                                }

                            } else {

                                $code = 412;
                            }

                        } else {
                            $code = 411;
                        }

                    } else {
                        $code = 410;

                    }

                } else {

                    $code = 408;
                    $msg  = "余额不足";
                }

            } else {
                $code = 407;
                $msg  = "转账手机号码有误";
            }
        } else {

            $code = 406;
            $msg  = "转账数量或者转账手机号码未输入";
        }

        if ($commit) {
            $code = 200;
            $this->db->commit();
        } else {
            $this->db->rollback();
        }
        $arr['code'] = $code;
        $arr['msg']  = $msg;
        return $arr;
    }
    // 获取用户资金
    public function getBalance()
    {
        $sql = "SELECT * FROM {$this->_prefix['primary']}finance_balance WHERE `uid`=" . $this->_user['uid'];
        return $this->db->getrow($sql);
    }

    //获取用户足迹
    public function getFootList($page, $pagesize = 10)
    {
        $sql = "SELECT COUNT(`id`) AS `cnt` FROM {$this->_prefix['primary']}goods_history WHERE `uid`=" . $this->_user['uid'];
        $cnt = $this->db->getone($sql);
        if ($cnt > 0) {

            $start = ($page - 1) * $pagesize;

            $sql = "SELECT `id`,`goods_id` FROM {$this->_prefix['primary']}goods_history WHERE  `uid`=" . $this->_user['uid'] . "  ORDER BY `create_time` DESC LIMIT " . $start . "," . $pagesize;

            $rs = $this->sql($sql);

            if ($rs) {
                foreach ($rs as $r) {

                    $goods_id[$r['goods_id']] = $r['goods_id'];
                }

                $sql = "SELECT `goods_id`,`goods_name`,`market_price`,`shop_price`,`thumb_docid`,`pic_docid`,`sales_count` FROM {$this->_prefix['primary']}goods_data WHERE `goods_id` IN (" . implode(",", $goods_id) . ") AND `is_on_sale`=1 AND `is_delete`=0";
                $tmp = $this->sql($sql);
                if ($tmp) {
                    foreach ($tmp as $r) {

                        $goods[$r['goods_id']] = $r;
                        if ($r['thumb_docid'] == 0 && $r['pic_docid'] > 0) {
                            $r['thumb_docid'] = $goods[$r['goods_id']]['thumb_docid'] = $r['pic_docid'];
                        }

                        if ($r['thumb_docid'] > 0) {
                            $docids[] = $r['thumb_docid'];
                        }

                        $goods_ids[] = $r['goods_id'];
                    }

                    if ($docids) {
                        $docs = $this->getDocs($docids);
                    }

                    // 获取库存
                    if ($goods_ids) {
                        $sql = "SELECT `goods_id`,`number` FROM {$this->_prefix['primary']}goods_stock WHERE `goods_id` IN (" . implode(",", $goods_ids) . ")";
                        $tmp = $this->sql($sql);
                        if ($tmp) {
                            foreach ($tmp as $r) {
                                $goods_stock[$r['goods_id']] = $r['number'];
                            }
                        }
                    }
                }

                foreach ($rs as $k => $r) {
                    if ($goods[$r['goods_id']]) {
                        $data[] = $goods[$r['goods_id']];

                        $index = count($data) - 1;

                        $data[$index]['goods_number'] = $goods_stock[$r['goods_id']] > 0 ? $goods_stock[$r['goods_id']] : 0;

                        if ($goods[$r['goods_id']]['thumb_docid'] > 0 && $docs[$goods[$r['goods_id']]['thumb_docid']]) {
                            $data[$index]['thumb_pic'] = $docs[$goods[$r['goods_id']]['thumb_docid']];
                        }
                    }
                }

            }
        }
        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt / $pagesize),
            'count'   => $cnt,
            'data'    => $data,

        );
    }

    //获取签到信息
    public function getSignInDetail()
    {
        $sql  = "SELECT * FROM {$this->_prefix['primary']}signin WHERE `uid`=" . $this->_user['uid'] . " ORDER BY `create_time` desc";
        $data = $this->db->getrow($sql);
        if ($data) {
            $data['sign_status'] = 0;
            $beginToday          = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
            $endToday            = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;

            $beginYesterday = mktime(0, 0, 0, date('m'), date('d') - 1, date('Y'));
            //$endYesterday=mktime(0,0,0,date('m'),date('d'),date('Y'))-1;
            //echo date("Y-m-d H:i",$data['create_time'])."===".date("Y-m-d H:i",$beginToday);die;
            if ($data['create_time'] >= $beginToday && $data['create_time'] < $endToday) {

                $data['sign_status'] = 1;

                return $data;
            } else {

                if ($data['create_time'] < $beginYesterday || $data['day_num'] >= 7) {

                    $data['day_num'] = 0;

                    return $data;
                }

            }

        }

        return $data;

    }
    //签到处理
    public function saveSign()
    {
        $config       = $this->getSetting();
        $data['code'] = 900;
        $data['msg']  = "签到失败";

        if (!$config['sign_status']) {

            return array('code' => 901, 'msg' => "签到已关闭");
        }
        $this->db->begin();
        $commit       = false;
        $sign         = $this->getSignInDetail();
        $f['day_num'] = 1;
        if ($sign) {
            $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
            $endToday   = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;

            if ($sign['create_time'] >= $beginToday && $sign['create_time'] < $endToday) {

                return array('code' => 902, 'msg' => "您已签到");
            }

            $beginYesterday = mktime(0, 0, 0, date('m'), date('d') - 1, date('Y'));
            $endYesterday   = mktime(0, 0, 0, date('m'), date('d'), date('Y')) - 1;

            if ($sign['create_time'] >= $beginYesterday && $sign['create_time'] < $endYesterday) {
                $f['day_num'] = $sign['day_num'] + 1;

            }

        }
        $f['create_time'] = time();
        $f['uid']         = $this->_user['uid'];
        $type             = true;
        $msg              = "金花";
        if ($config['gold_money'][$f['day_num']]) {
            $set = "`gold_money`=`gold_money`+";

            $money = $config['gold_money'][$f['day_num']];
        } else {
            $type  = false;
            $msg   = "代金券";
            $money = $config['coupon_money'][$f['day_num']];
            $set   = "`coupon`=`coupon`+";
        }
        $f['money'] = empty($money) ? 0 : $money;

        $sign_id = $this->table('signin')->insert($f);
        if ($sign_id) {
            if ($f['money']) {
                $balance = $this->getBalance();
                // 更新资金表
                $sql = "UPDATE {$this->_prefix['primary']}finance_balance SET " . $set . $f['money'] . " WHERE `uid`=" . $balance['uid'];
                $rcs = $this->sql($sql);
                if ($rcs > 0) {
                    $detail_note = "签到送" . $msg;
                    $event       = 25;
                    if ($type) {

                        $balance_money = $balance['gold_money'];
                    } else {

                        $balance_money = $balance['coupon'];
                    }
                    $sql       = "INSERT INTO {$this->_prefix['primary']}finance_detail (`uid`,`event`,`cmoney`,`money`,`create_time`,`note`,`dataid`,`table_name`) VALUES (" . $balance['uid'] . "," . $event . "," . $f['money'] . "," . ($balance_money + $f['money']) . "," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "'," . $sign_id . ",'signin')";
                    $detail_id = $this->sql($sql);
                    if ($detail_id) {

                        $commit = true;

                    }

                }

            } else {
                $commit = true;

            }

            if ($commit) {
                $data['code'] = 200;
                $data['msg']  = "签到获得" . $f['money'] . "个" . $msg;
                $this->db->commit();
            } else {

                $this->db->rollback();
            }

        }

        return $data;
    }

    //清除足迹
    public function delFoots()
    {
        $sql = "DELETE FROM {$this->_prefix['primary']}goods_history WHERE `uid`=" . $this->_user['uid'];
        $res = $this->sql($sql);
        if ($res) {
            $data['code'] = 200;
            $data['msg']  = "清空足迹成功";
        } else {
            $data['code'] = 900;
            $data['msg']  = "清空足迹失败，请重试！";
        }
        return $data;
    }

    //查出用户支付订单信息
    public function getMember($uid = 0)
    {
        if (!$uid) {
            $uid = $this->_user['uid'];
        }
        $sql = "SELECT * FROM {$this->_prefix['primary']}member_account WHERE `uid`=" . $uid;
        return $this->db->getrow($sql);
    }

    //提交代理升级申请
    public function subUpgrade($da)
    {
        $uid         = intval($da['uid']);
        $agent_level = intval($da['type']);
        $setting_id  = intval($da['settingId']);
        $arr['code'] = 900;
        $arr['msg']  = "提交失败";
        if ($uid > 0 && $agent_level > 1 && $setting_id > 0) {
            $member = $this->getMember($uid);
            if ($member['level_type'] == 2 && $agent_level > $member['agent_level']) {

                $field['uid']         = $this->_user['uid'];
                $field['agent_uid']   = $member['uid'];
                $field['old_level']   = $member['agent_level'];
                $field['new_level']   = $agent_level;
                $field['setting_id']  = $setting_id;
                $field['create_time'] = time();
                $aid                  = $this->table("agent_upgrade")->insert($field);

                if ($aid) {
                    $arr['code'] = 200;
                    $arr['msg']  = "提交成功，请等待审核！";

                }

            } else {
                $arr['code'] = 902;
                $arr['msg']  = "不是代理商或者升级等级过低，不能升级";

            }

        } else {
            $arr['code'] = 901;

        }

        return $arr;

    }

    //创建开通会员订单
    public function createMemberOrder($da)
    {
        $code = 900;

        // $money_array = array(365, 1500, 6000);
        $money  = $level_money  = intval($da['money']);
        $paid   = false;
        $config = $this->getSetting();
        if ($money > 0 && intval($config['vip_price']) == $money) {

            // 默认微信
            $pay_type   = 0;
            $order_type = 0;
            $order_sn   = date("YmdHis") . rand(1000, 9999) . $this->_user['uid'];

            /*   if ($money == 365) {
            $money = number_format("364." . rand(10, 99), 2, ".", "");
            } */
            // 插入开通订单
            $sql = "INSERT INTO {$this->_prefix['primary']}member_payinfo (
            `uid`,
            `order_sn`,
            `money`,
            `level_money`,
            `ctime`,
            `pay_type`,
            `order_type`
            ) VALUES (
            " . $this->_user['uid'] . ",
            '" . $order_sn . "',
            " . $money . ",
            " . $level_money . ",
            " . $_SERVER['REQUEST_TIME'] . ",
            " . $pay_type . ",
            " . $order_type . "
            )";

            $order_id = $this->sql($sql);

            if ($order_id > 0) {
                $code = 200;
                // 检查用户九妹币是否充足
                $balance = $this->getBalance();
                if ($balance['gold_money'] >= $level_money) {

                    $this->db->begin();
                    $commit = false;
                    $code   = 403;

                    $past_time = strtotime("+1 years");

                    // 更新开通会员订单表
                    $sql = "UPDATE {$this->_prefix['primary']}member_payinfo SET `pay_status`=2,`pay_type`=4,`pay_time`=" . $_SERVER['REQUEST_TIME'] . ",`past_time`=" . $past_time . ",`money`=" . $level_money . " WHERE `order_id`=" . $order_id;
                    $rcs = $this->sql($sql);
                    if ($rcs > 0) {
                        $member_level = 1;
                        /*        if ($level_money == 365) {
                        $member_level = 1;
                        } elseif ($level_money == 1500) {
                        $member_level = 2;
                        } elseif ($level_money == 6000) {
                        $member_level = 3;
                        } */

                        // 更新会员等级与到期时间
                        $sql = "UPDATE {$this->_prefix['primary']}member_account SET `member_level`=" . $member_level . ",`level_time`=" . $_SERVER['REQUEST_TIME'] . ",`level_past_time`=" . $past_time . " WHERE `uid`=" . $this->_user['uid'];
                        $rcu = $this->sql($sql);

                        if ($rcu > 0) {

                            // 更新资金表
                            $sql = "UPDATE {$this->_prefix['primary']}finance_balance SET `gold_money`=`gold_money`-" . $level_money . " WHERE `uid`=" . $balance['uid'];
                            $rcs = $this->sql($sql);
                            if ($rcs > 0) {
                                $detail_note = "开通订单号" . $order_sn . ",金豆抵扣成功";
                                $event       = 13;
                                $sql         = "INSERT INTO {$this->_prefix['primary']}finance_detail (`uid`,`event`,`cmoney`,`money`,`create_time`,`note`,`dataid`,`table_name`) VALUES (" . $balance['uid'] . "," . $event . "," . $level_money . "," . ($balance['gold_money'] - $level_money) . "," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "'," . $order_id . ",'member_payinfo')";
                                $detail_id   = $this->sql($sql);
                                if ($detail_id) {

                                    $paid   = true;
                                    $commit = true;
                                    $code   = 200;

                                }

                            }

                        }

                    }

                    if ($commit) {
                        $this->db->commit();
                    } else {
                        $this->db->rollback();
                    }

                }

            } else {
                $code = 403;
            }
        }

        return array(
            'code'     => $code,
            'order_id' => $order_id,
            'pay_fee'  => $money,
            'paid'     => $paid,
        );

    }

    //查出推荐码
    public function getRecode()
    {
        $sql         = "SELECT * FROM {$this->_prefix['primary']}member_account WHERE `uid`=" . $this->_user['uid'];
        $member_info = $this->db->getrow($sql);
        if (!empty($member_info)) {

            return $member_info;
        }
    }

    public function getUserAccountInfo()
    {

        $sql  = "SELECT * FROM  {$this->_prefix['primary']}member_account  WHERE uid={$this->_user['uid']} limit 1";
        $info = $this->db->getrow($sql);
        return $info;

    }

    public function getUserProfileInfo()
    {

        $sql  = "SELECT * FROM  {$this->_prefix['primary']}member_profile  WHERE uid={$this->_user['uid']} limit 1";
        $info = $this->db->getrow($sql);
        if ($info['province_id'] > 0) {
            $region_ids[] = $info['province_id'];
        }

        if ($info['city_id'] > 0) {
            $region_ids[] = $info['city_id'];
        }

        if ($info['county_id'] > 0) {
            $region_ids[] = $info['county_id'];
        }

        if ($region_ids) {
            $region = $this->getRegionWithId($region_ids);
        }

        return array('info' => $info, "region" => $region);
    }

    //获取用户详细信息
    public function getUserMore()
    {

        $sql            = "SELECT * FROM {$this->_prefix['primary']}member_account WHERE `uid`=" . $this->_user['uid'];
        $user           = $this->db->getrow($sql);
        $sql            = "SELECT * FROM {$this->_prefix['primary']}member_wechat WHERE `uid`=" . $this->_user['uid'];
        $user['wechat'] = $this->db->getrow($sql);
        $sql            = "SELECT `money`,`freeze` FROM {$this->_prefix['primary']}finance_balance WHERE `uid`=" . $this->_user['uid'];
        $row            = $this->db->getrow($sql);
        $user['money']  = $row['money'];
        $user['freeze'] = $row['freeze'];

        return $user;
    }

    // 获取区域信息
    public function getRegion($parent_id = 0)
    {
        $sql = "SELECT `region_id`,`region_name` FROM {$this->_prefix['primary']}region WHERE `parent_id`=" . intval($parent_id);

        $data = $this->sql($sql);
        if ($data) {
            foreach ($data as $r) {
                $new[$r['region_id']] = $r['region_name'];
            }
            return $new;
        } else {
            return false;
        }

    }

    //修改手机号码
    public function updateUserMobile($da)
    {
        $code     = 900;
        $mobile   = addslashes(htmlspecialchars(trim($da['mobile'])));
        $smscode  = intval($da['smscode']);
        $recode   = addslashes(htmlspecialchars(trim($da['recode'])));
        $realname = addslashes(htmlspecialchars(trim($da['realname'])));

        $pid = 0;

        if (preg_match("/^(13|14|15|16|17|18|19)([0-9]{9})$/", $mobile)) {
            $sql   = "SELECT `uid` FROM {$this->_prefix['primary']}member_account WHERE `mobile`=" . $mobile . " LIMIT 1";
            $exuid = $this->db->getone($sql);
            if (!$exuid) {
                $this->db->begin();
                $next = true;

                if ($recode != "") {
                    $next    = false;
                    $sql     = "SELECT `uid`,`level_type` FROM {$this->_prefix['primary']}member_account WHERE `recode`='" . $recode . "' AND `stat`=1 ORDER BY `uid` DESC LIMIT 1";
                    $pmember = $this->db->getrow($sql);
                    $pid     = $pmember['uid'];
                    if ($pid > 0) {
                        // 赠送免邮券
                        $couponsql          = "INSERT INTO {$this->_prefix['primary']}discount_coupon (`uid`,`money`,`need_money`,`create_time`,`expire_time`,`type`) VALUES ";
                        $coupon_money       = 8;
                        $coupon_need_money  = 0;
                        $coupon_type        = 1;
                        $coupon_create_time = $_SERVER['REQUEST_TIME'];
                        $coupon_expire_time = strtotime("+1 months");
                        $couponsql .= "(" . $this->_user['uid'] . "," . $coupon_money . "," . $coupon_need_money . "," . $coupon_create_time . "," . $coupon_expire_time . "," . $coupon_type . "),
                        (" . $this->_user['uid'] . "," . $coupon_money . "," . $coupon_need_money . "," . $coupon_create_time . "," . $coupon_expire_time . "," . $coupon_type . "),
                        (" . $this->_user['uid'] . "," . $coupon_money . "," . $coupon_need_money . "," . $coupon_create_time . "," . $coupon_expire_time . "," . $coupon_type . "),
                        (" . $this->_user['uid'] . "," . $coupon_money . "," . $coupon_need_money . "," . $coupon_create_time . "," . $coupon_expire_time . "," . $coupon_type . "),
                        (" . $pid . "," . $coupon_money . "," . $coupon_need_money . "," . $coupon_create_time . "," . $coupon_expire_time . "," . $coupon_type . ")";
                        // 判断是否扫码并赠送满抵券
                        if ($_SESSION['qrcode_recode'] == $recode) {
                            $coupon_money       = 10;
                            $coupon_need_money  = 200;
                            $coupon_type        = 2;
                            $coupon_create_time = $_SERVER['REQUEST_TIME'];
                            $coupon_expire_time = strtotime("+1 months");
                            $couponsql .= ",(" . $this->_user['uid'] . "," . $coupon_money . "," . $coupon_need_money . "," . $coupon_create_time . "," . $coupon_expire_time . "," . $coupon_type . ")";
                        }

                        $rcp = $this->sql($couponsql);
                        if ($rcp > 0) {
                            $next = true;
                        } else {
                            $code = 904;
                        }
                    } else {
                        $code = 905;
                    }
                }

                if ($next) {

                    $setting    = $this->getSetting();
                    $start_time = $setting['bind_start_time'] ? strtotime($setting['bind_start_time']) : 0;
                    $end_time   = $setting['bind_end_time'] ? strtotime($setting['bind_end_time']) : 0;
                    if ($setting['bind_status'] == 1 && ($setting['bind_ximi_money'] > 0 || $setting['bind_coupon'] > 0) && $_SERVER['REQUEST_TIME'] > $start_time && $_SERVER['REQUEST_TIME'] < $end_time) {
                        $next    = false;
                        $field   = array();
                        $balance = $this->getBalance();
                        $event   = 27;
                        //金花
                        if ($setting['bind_ximi_money'] > 0) {
                            $field[] = "`gold_money` = " . fun_price($balance['gold_money'] + $setting['bind_ximi_money']);

                            //保存硒米
                            $detail_note = "绑定手机赠送金花";
                            $sql         = "INSERT INTO {$this->_prefix['primary']}finance_detail (`uid`,`event`,`cmoney`,`money`,`create_time`,`note`,`dataid`,`table_name`) VALUES (" . $this->_user['uid'] . "," . $event . "," . $setting['bind_ximi_money'] . "," . (fun_price($balance['gold_money'] + $setting['bind_ximi_money'])) . "," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "'," . $balance['uid'] . ",'member_account')";
                            $detail_id   = $this->sql($sql);

                            if ($detail_id) {

                                $next = true;
                            }

                        } else {

                            $next = true;
                        }
                        //代金券
                        if ($setting['bind_coupon'] > 0 && $next) {
                            $field[] = "`coupon` = " . fun_price($balance['coupon'] + $setting['bind_coupon']);
                            //保存硒米
                            $detail_note = "绑定手机赠送代金券";
                            $sql         = "INSERT INTO {$this->_prefix['primary']}finance_detail (`uid`,`event`,`cmoney`,`money`,`create_time`,`note`,`dataid`,`table_name`) VALUES (" . $this->_user['uid'] . "," . $event . "," . $setting['bind_coupon'] . "," . (fun_price($balance['coupon'] + $setting['bind_coupon'])) . "," . $_SERVER['REQUEST_TIME'] . ",'" . $detail_note . "'," . $balance['uid'] . ",'member_account')";
                            $next        = $this->sql($sql);

                        }

                        if ($next) {
                            //赠送
                            $sql  = "UPDATE {$this->_prefix['primary']}finance_balance SET " . implode(",", $field) . ",`last_edit`=" . $_SERVER['REQUEST_TIME'] . ",`update_time`=" . $_SERVER['REQUEST_TIME'] . ",`random_num`=" . rand(100000, 999999) . " WHERE `uid`=" . $this->_user['uid'];
                            $next = $this->sql($sql);

                        }

                    }

                }

                if ($next) {
                    $next = false;
                    $rsd  = $this->doCheckSms($mobile, $smscode);
                    // 如果验证码可用
                    if ($rsd['code'] == 200) {

                        //生成邀请码

                        $tsql = '';

                        if ($pid > 0) {
                            $tsql .= ",`pid`=" . $pid;
                        }

                        // 获取机制排序号码
                        $sql        = "SELECT `id`,`number` FROM {$this->_prefix['primary']}member_no WHERE `level_type`=1";
                        $nos        = $this->db->getrow($sql);
                        $new_number = $nos['number'] + 1;
                        if (substr($new_number, -1) == "4") {
                            $new_number += 1;
                        }
                        $newrecode = $new_number;

                        $sql = "UPDATE {$this->_prefix['primary']}member_account SET `recode`='" . $newrecode . "',`bind_time`=" . $_SERVER['REQUEST_TIME'] . ",`mobile`='" . $mobile . "',`name`='" . $realname . "'" . $tsql . " WHERE `uid`=" . $this->_user['uid'];
                        $rs  = $this->sql($sql);
                        if ($rs > 0) {

                            // 更新机制排序号码
                            $sql  = "UPDATE {$this->_prefix['primary']}member_no SET `number`=" . $new_number . " WHERE `id`=" . $nos['id'];
                            $rcno = $this->sql($sql);
                            if ($rcno > 0) {
                                $code = 200;
                                $next = true;
                            } else {
                                $code = 905;
                            }
                        } else {
                            $coed = 904;
                        }

                    } else {
                        $code = 901;
                    }
                }

                if ($next) {
                    $this->db->commit();
                } else {
                    $this->db->rollback();
                }

            } else {

                $code = 903;
            }

        } else {

            $code = 902;
        }
        return $code;
    }

    public function getMemberName()
    {
        $mobile = input_str('mobile');
        $name = "";
        $where = " `recode`='".$mobile."'";
        if(strlen($mobile)==11){
            /*  if(preg_match("/^(13|14|15|16|17|18|19)([0-9]{9})$/", $mobile)){

                   return $this->error("手机格式不正确");
               }*/

            $where = " `mobile`='".$mobile."'";
        }

        $data = $this->table("member_account")->findBySql($where." AND `stat`=1");

        if($data){
            $name = $data['realname'];
            if($data['name']){
                $name = $data['name'];

            }
        }
        return $name;

    }

    //保存个人资料地区
    public function saveUserAccount($data)
    {
        $code = 900;
        unset($data['act']);
        $rollback = true;
        $this->db->begin();

        $sql   = "SELECT COUNT(*) FROM {$this->_prefix['primary']}member_profile where uid=" . $this->_user['uid'];
        $count = $this->db->getone($sql); //没有记录新增 有记录更新
        if ($count == 0) {
            $data['uid'] = $this->_user['uid'];
        }

        $update_str   = "";
        $insert_key   = "";
        $insert_value = "";
        foreach ($data as $k => $v) {
            if (!empty($v)) {
                $v = addslashes(stripcslashes(trim($v)));
                $update_str .= "`" . $k . "`='" . $v . "',";
                $insert_key .= "`" . $k . "`,";
                $insert_value .= "'" . $v . "',";
            }
        }

        if ($update_str != "" && $count > 0) {
            $update_str = substr($update_str, 0, strlen($update_str) - 1);

            $sql = "UPDATE {$this->_prefix['primary']}member_profile set " . $update_str . " where uid={$this->_user['uid']}";
            $rs  = $this->sql($sql);
            if ($rs) {
                $rollback = false;
                $code     = 200;
            }
        } elseif ($insert_key != "" && $count == 0) {
            $insert_key   = substr($insert_key, 0, strlen($insert_key) - 1);
            $insert_value = substr($insert_value, 0, strlen($insert_value) - 1);
            $sql          = "INSERT INTO {$this->_prefix['primary']}member_profile(" . $insert_key . ") values(" . $insert_value . ")";
            $rs           = $this->sql($sql);
            if ($rs) {
                $rollback = false;
                $code     = 200;
            }

        }

        if ($rollback) {
            $this->db->rollback();
        } else {
            $this->db->commit();
        }

        return $code;
    }

    //收货地址列表
    public function list_user_address($para, $page = 1, $pagesize = 10)
    {

        $where = "";
        if ($para) {

            if ($para['keyword'] != '') {
                $where .= " AND `realname` LIKE '%" . $para['keyword'] . "%'";
            }

            if ($para['uid'] > 0) {
                $where .= " AND uid=" . $para['uid'];
            }

        }

        $sql = "SELECT COUNT(`id`) AS `cnt` FROM {$this->_prefix['primary']}member_address WHERE 1 " . $where;

        $cnt = $this->sql($sql);
        if ($cnt[0]['cnt'] > 0) {

            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "`is_default` DESC,`id` DESC";

            $sql = "SELECT * FROM {$this->_prefix['primary']}member_address WHERE 1 " . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;
            $rs  = $this->sql($sql);
            if ($rs) {
                foreach ($rs as $key => $val) {
                    if ($val['province_id'] > 0) {
                        $region_ids[] = $val['province_id'];
                    }

                    if ($val['city_id'] > 0) {
                        $region_ids[] = $val['city_id'];
                    }

                    if ($val['county_id'] > 0) {
                        $region_ids[] = $val['county_id'];
                    }

                }
                if ($region_ids) {
                    $region = $this->getRegionWithId($region_ids);
                }

            }

        }

        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt[0]['cnt'] / $pagesize),
            'count'   => $cnt[0]['cnt'],
            'data'    => $rs,
            'para'    => $para,
            'region'  => $region,
        );
    }

    public function set_user_address($id, $uid)
    {
        if ($id > 0 && $uid > 0) {
            $where = " AND id=$id AND uid=$uid";
            $sql   = "UPDATE {$this->_prefix['primary']}member_address SET is_default=0 WHERE 1 AND uid={$uid} AND is_default=1";
            $rs    = $this->sql($sql);

            $sql = "UPDATE {$this->_prefix['primary']}member_address SET is_default=1 WHERE 1 " . $where . " LIMIT 1";
            $rs  = $this->sql($sql);
        }
        return true;
    }

    // 保存收货地址
    public function saveAddress($da)
    {
        $code = 900;

        $realname    = addslashes(stripcslashes(trim($da['realname'])));
        $idnum       = strtolower(addslashes(stripcslashes(trim($da['idnum']))));
        $mobile      = addslashes(stripcslashes(trim($da['mobile'])));
        $address     = addslashes(stripcslashes(trim($da['address'])));
        $region      = addslashes(stripcslashes(trim($da['region'])));
        $is_default  = intval($da['is_default']);
        $region      = explode(",", $region);
        $province_id = intval($region[0]);
        $city_id     = intval($region[1]);
        $county_id   = intval($region[2]);

        if ($realname != "" && $mobile != "" && $address != "" && $province_id > 0 && $city_id > 0) {
            $sql = "INSERT INTO {$this->_prefix['primary']}member_address (`uid`,`realname`,`idnum`,`mobile`,`address`,`province_id`,`city_id`,`county_id`,`is_default`) VALUES (" . $this->_user['uid'] . ",'" . $realname . "','" . $idnum . "','" . $mobile . "','" . $address . "'," . $province_id . "," . $city_id . "," . $county_id . "," . $is_default . ")";

            $id = $this->sql($sql);
            if ($id > 0) {
                $code = 200;
                if ($is_default == 1) {
                    //默认大于0  修改其它地址为非默认。
                    $sql = "UPDATE {$this->_prefix['primary']}member_address SET is_default=0 where uid={$this->_user['uid']} and id!=" . $id;
                    $this->sql($sql);
                }

            } else {
                $code = 403;
            }

        }

        return $code;

    }

    //编辑地址
    public function updateAddress($da)
    {
        $code     = 900;
        $where    = "";
        $realname = addslashes(stripcslashes(trim($da['realname'])));
        $idnum    = addslashes(stripcslashes(trim($da['idnum'])));
        $mobile   = addslashes(stripcslashes(trim($da['mobile'])));
        if (!strpos($idnum, '*')) {

            $where = ",idnum='{$idnum}'";
        }

        if (!strpos($mobile, '*')) {

            $where .= ",mobile='{$mobile}'";
        }

        $address     = addslashes(stripcslashes(trim($da['address'])));
        $region      = addslashes(stripcslashes(trim($da['region'])));
        $is_default  = intval($da['is_default']);
        $region      = explode(",", $region);
        $province_id = intval($region[0]);
        $city_id     = intval($region[1]);
        $county_id   = intval($region[2]);
        $id          = intval($da['id']);
        if ($realname != "" && $mobile != "" && $address != "" && $province_id > 0 && $city_id > 0 && $id > 0) {
            $sql = "update  {$this->_prefix['primary']}member_address set realname='{$realname}'" . $where . ",address='{$address}',province_id={$province_id},city_id={$city_id},county_id={$county_id},is_default={$is_default} where id=" . $id;
            $rs  = $this->sql($sql);
            if ($rs) {
                $code = 200;
                if ($is_default == 1) {
                    //默认大于0  修改其它地址为非默认。
                    $sql = "UPDATE {$this->_prefix['primary']}member_address SET is_default=0 where uid={$this->_user['uid']} and id!=" . $id;
                    $this->sql($sql);
                }

            } else {
                $code = 403;
            }

        }

        return $code;

    }

    // 获取区域信息

    public function getRegionNew()
    {
        $sql = "SELECT `region_id`,`region_name`,`parent_id` FROM {$this->_prefix['primary']}region ORDER BY `parent_id` ASC,`region_id` ASC";

        $data = $this->sql($sql);
        if ($data) {
            foreach ($data as $r) {
                $new[$r['parent_id']][$r['region_id']] = $r;
            }
            return $new;
        }

    }

    //地址判断
    public function address_number()
    {
        $code = 900;
        $sql  = "SELECT COUNT(`id`) AS `cnt` FROM {$this->_prefix['primary']}member_address WHERE `uid`=" . $this->_user['uid'];
        $cnt  = $this->sql($sql);
        if ($cnt) {
            if ($cnt[0]['cnt'] < 3) {
                //地址不能超过三个
                $code = 200;
            }
            return $code;
        }

    }

    public function del_user_address($id, $uid)
    {
        if ($id > 0 && $uid > 0) {
            $where = " AND id=$id AND uid=$uid";
            $sql   = "DELETE FROM {$this->_prefix['primary']}member_address WHERE 1 " . $where . " LIMIT 1";
            $rs    = $this->sql($sql);
        }
        return true;
    }

    public function getRegionWithId($region_id)
    {
        if (is_array($region_id)) {
            $tsql = " IN (" . implode(",", $region_id) . ")";
        } else {
            $tsql = "=" . $region_id;
        }

        $sql = "SELECT `region_id`,`region_name` FROM {$this->_prefix['primary']}region WHERE `region_id`" . $tsql;

        $data = $this->sql($sql);
        if ($data) {
            foreach ($data as $r) {
                $new[$r['region_id']] = $r['region_name'];
            }
            return $new;
        } else {
            return false;
        }

    }

    //获取用户地址详情
    public function getAddrInfo($id)
    {

        $sql  = "select * from {$this->_prefix['primary']}member_address where id=" . $id;
        $info = $this->db->getrow($sql);
        if ($info['province_id'] > 0) {
            $region_ids[] = $info['province_id'];
        }

        if ($info['city_id'] > 0) {
            $region_ids[] = $info['city_id'];
        }

        if ($info['county_id'] > 0) {
            $region_ids[] = $info['county_id'];
        }

        if ($region_ids) {
            $region = $this->getRegionWithId($region_ids);
        }

        return array("info" => $info, 'region' => $region);
    }

    //获取推荐用户
    public function recommend($para, $page, $pagesize = 10)
    {
        $where = '';
        if ($para) {

            if ($para['keyword'] != '') {
                if (is_numeric($para['keyword'])) {
                    $where .= " AND (`recode`='" . $para['keyword'] . "' OR `mobile`='" . $para['keyword'] . "')";
                } else {
                    $where .= " AND `name` LIKE '%" . $para['keyword'] . "%'";
                }

            }

        }

        $sql = "SELECT COUNT(`uid`) AS `cnt` FROM {$this->_prefix['primary']}member_account WHERE `pid`=" . $this->_user['uid'] . " AND `stat`=1" . $where;
        $cnt = $this->db->getone($sql);
        if ($cnt > 0) {

            $start = ($page - 1) * $pagesize;
            $sql   = "SELECT * FROM {$this->_prefix['primary']}member_account WHERE `pid` =" . $this->_user['uid'] . " AND `stat`=1 " . $where . " ORDER BY `member_level` DESC,`level_time` DESC  LIMIT " . $start . "," . $pagesize;
            $data  = $this->db->sql($sql);
            foreach ($data as $k => &$v) {
                if ($v['headimgurl'] > 0) {

                    $pic                    = $this->getPic($v['headimgurl']);
                    $data[$k]['headimgurl'] = $pic[0]['img_url'];
                }
                if ($v['uid']) {

                    $count             = $this->getmemberCount($v['uid']);
                    $data[$k]['count'] = $count + 1;

                    //查出是否应该有升级申请
                    $agent_num             = $this->table("agent_upgrade")->countBySql("`agent_uid`=" . $v['uid'] . " AND `stat` =0");
                    $data[$k]['agent_num'] = $agent_num;
                }

                $data[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);

            }

        }
        // print_r($data);die;
        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt / $pagesize),
            'count'   => $cnt,
            'data'    => $data,

        );

    }

    //获取推荐用户
    public function subordinate($uid, $para, $page, $pagesize = 20)
    {
        $where = '';
        if ($para) {

            if ($para['keyword'] != '') {
                if (is_numeric($para['keyword'])) {
                    $where .= " AND (`recode`='" . $para['keyword'] . "' OR `mobile`='" . $para['keyword'] . "')";
                } else {
                    $where .= " AND `name` LIKE '%" . $para['keyword'] . "%'";
                }

            }

        }
        $sql = "SELECT COUNT(*) AS `cnt` FROM {$this->_prefix['primary']}member_account WHERE `pid`=" . $uid . " AND `stat`=1" . $where;
        $cnt = $this->db->getone($sql);
        if ($cnt > 0) {

            $start = ($page - 1) * $pagesize;
            $sql   = "SELECT * FROM {$this->_prefix['primary']}member_account WHERE `pid`=" . $uid . " AND `stat`=1 " . $where . " ORDER BY `member_level` DESC,`level_time` DESC  LIMIT " . $start . "," . $pagesize;
            $data  = $this->db->sql($sql);
            foreach ($data as $k => &$v) {
                if ($v['headimgurl'] > 0) {

                    $pic                    = $this->getPic($v['headimgurl']);
                    $data[$k]['headimgurl'] = $pic[0]['img_url'];
                }
                if ($v['uid']) {

                    $count             = $this->getmemberCount($v['uid']);
                    $data[$k]['count'] = $count + 1;
                }
                $data[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);

            }

        }
        return array(
            'page'    => $page,
            'maxpage' => ceil($cnt / $pagesize),
            'count'   => $cnt,
            'data'    => $data,

        );
    }

    //获取优惠卷
    public function coupon($type)
    {
        $where = "`uid` =" . $this->_user['uid'] . " AND status IN(0,1,4)";

        if ($type) {
            $type = $type - 1;
            $where .= " AND `status`=" . $type;
            if ($type == 4) {
                $where .= " AND `expire_time` < " . $_SERVER['REQUEST_TIME'];

            }
        }

        $sql  = "SELECT * FROM {$this->_prefix['primary']}discount_coupon WHERE " . $where . " ORDER BY coupon_id DESC ";
        $data = $this->db->sql($sql);

        foreach ($data as $key => $val) {
            if ($val['status'] == 1) {

                $data[$key]['status'] = "已使用";
            } elseif ($val['status'] == 4) {

                $data[$key]['status'] = "已过期";
            } else {

                $data[$key]['status'] = "未使用";
            }
            $data[$key]['create_time'] = date('Y-m-d H:i:s', $val['create_time']);
            $data[$key]['expire_time'] = date('Y-m-d H:i:s', $val['expire_time']);

            if ($val['used_time'] > 0) {
                $data[$key]['used_time'] = date('Y-m-d H:i:s', $val['used_time']);
            }

            if ($val['type'] == 1) {
                $data[$key]['type_price'] = "免运费劵 " . $val['money'];

            } elseif ($val['type'] == 2) {
                $data[$key]['type_price'] = "满" . $val['need_money'] . "抵" . ($val['money'] * 1) . "优惠券";
            }
        }

        return array(
            'data' => $data,
        );

    }

    //商品图片
    public function getDocs($docid)
    {
        if (is_array($docid)) {
            $where = " WHERE `docid` IN (" . implode(",", array_unique($docid)) . ")";
        } else {
            $where = " WHERE `docid`=" . intval($docid);
        }

        $sql = "SELECT `docid`,`filename`,`create_time` FROM {$this->_prefix['primary']}documents " . $where;
        $rs  = $this->sql($sql);
        if ($rs) {
            foreach ($rs as $r) {
                $doc[$r['docid']] = $this->c['doc_host'] . date("Ymd", $r['create_time']) . "/" . date("H", $r['create_time']) . "/" . date("i", $r['create_time']) . "/" . $r['filename'];

            }
            return $doc;
        } else {
            return false;
        }

    }

    // 发送短信验证码
    public function sendSMScode($da)
    {
        $code = 900;

        $mobile = addslashes(stripcslashes(trim($da['mobile'])));

        // 检查手机号码格式
        if (preg_match("/^(13|14|15|16|17|18|19)([0-9]{9})$/", $mobile)) {

            // 检查手机号码是否已经注册
            $sql   = "SELECT `uid` FROM {$this->_prefix['primary']}member_account WHERE `mobile`='" . $mobile . "' LIMIT 1";
            $exuid = $this->db->getone($sql);
            if (!$exuid) {
                // 发送短信验证码
                $rs     = $this->doSendSms($mobile);
                $code   = $rs['code'];
                $errmsg = $rs['errmsg'];
            } else {
                $code = 404;
            }

        }

        return array(
            'code'   => $code,
            'errmsg' => $errmsg,
        );
    }

    // 执行发送短信验证码
    public function doSendSms($mobile)
    {
        $code = 900;

        $this->db->begin();
        $commit  = false;
        $smscode = rand(100000, 999999);

        $sql   = "INSERT INTO {$this->_prefix['primary']}sms (`mobile`,`smscode`,`create_time`) VALUES (" . $mobile . "," . $smscode . "," . $_SERVER['REQUEST_TIME'] . ")";
        $smsid = $this->sql($sql);
        if ($smsid > 0) {
            $code = 409;

            $url = "http://submit.10690221.com:9011/send/ordinarykv?";

            $para['uid']      = "110364";
            $para['password'] = md5("1q2w3e4r5t");
            $para['mobile']   = $mobile;
            $para['msg']      = urlencode("【西海良品】您的验证码是：" . $smscode . "");

            foreach ($para as $key => $value) {
                $pv[] = $key . "=" . $value;
            }

            $url .= implode("&", $pv);

            $json_result = file_get_contents($url);
            if ($json_result != "") {
                $json = json_decode($json_result, true);
            }

            if ($json['code'] == "0" && strlen($json['msgId']) > 3) {
                $code   = 200;
                $commit = true;
            } else {
                $errmsg = $json['msg'];
            }

        }

        if ($commit) {
            $this->db->commit();
        } else {
            $this->db->rollback();

        }

        return array(
            'code'   => $code,
            'errmsg' => $errmsg,
        );
    }

    // 执行检查短信验证码
    public function doCheckSms($mobile, $smscode)
    {
        $code = 900;

        $sql     = "SELECT `data_id` FROM {$this->_prefix['primary']}sms WHERE `mobile`=" . $mobile . " AND `smscode`=" . intval($smscode) . " AND `is_used`=0 ORDER BY `create_time` DESC LIMIT 1";
        $data_id = $this->db->getone($sql);
        if ($data_id > 0) {
            $code = 403;
            $sql  = "UPDATE {$this->_prefix['primary']}sms SET `is_used`=1,`used_time`=" . $_SERVER['REQUEST_TIME'] . " WHERE `data_id`=" . $data_id;
            $rcs  = $this->sql($sql);
            if ($rcs > 0) {
                $code = 200;
            }

        }

        return array(
            'code' => $code,
        );

    }

    public function saveUserName($da)
    {
        $arr         = array();
        $arr['code'] = 900;
        $arr['msg']  = "修改失败，请重试！";
        $name        = addslashes(stripcslashes(trim($da['name'])));
        if (!empty($name)) {
            $sql = "UPDATE {$this->_prefix['primary']}member_account set name='" . $name . "' where uid=" . $this->_user['uid'];
            $rs  = $this->sql($sql);
            if ($rs) {

                $arr['code'] = 200;
                $arr['msg']  = "修改姓名成功！";
            }

        } else {
            $arr['code'] = 901;
            $arr['msg']  = "姓名不能为空";
        }
        return $arr;
    }

    public function downloadimageformweixin($url)
    {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_URL, $url);
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();

        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return $return_content;
    }

    //获取下级所有的UID
    public function getDownUid()
    {
        $sql  = "SELECT `uid` FROM {$this->_prefix['primary']}member_account WHERE `pid` =" . $this->_user['uid'] . " ORDER BY level_time DESC ";
        $data = $this->db->sql($sql);
        $uids = "";
        if ($data) {
            foreach ($data as $val) {

                $uids .= empty($uids) ? $val['uid'] : ',' . $val['uid'];
            }

        }
        return trim($uids);
    }

    //获取优惠券类型数量
    public function getCouponNum()
    {
        $count['coupon_total']  = 0;
        $count['coupon_unused'] = 0;
        $count['coupon_used']   = 0;
        $count['coupon_past']   = 0;
        $sql                    = "SELECT `status`,`uid`,`expire_time` FROM {$this->_prefix['primary']}discount_coupon WHERE `uid`=" . $this->_user['uid'];
        $data                   = $this->sql($sql);

        if ($data) {
            foreach ($data as $val) {

                if ($val['status'] == 0) {
                    $count['coupon_unused'] += 1;

                } else if ($val['status'] == 1) {
                    $count['coupon_used'] += 1;

                } else if ($val['status'] == 4) {
                    $count['coupon_past'] += 1;

                }
            }
            $count['coupon_total'] = count($data);
        }
        return $count;
    }

    // 检查未领取的套餐
    public function checkTao()
    {
        $sql  = "SELECT `order_id`,`level_money` FROM {$this->_prefix['primary']}member_payinfo WHERE `uid`=" . $this->_user['uid'] . " AND `pay_status`=2 AND `is_received`=0 ORDER BY `order_id` ASC LIMIT 1";
        $data = $this->db->getrow($sql);
        if ($data) {
            return $data;
        }
    }

    public function getmemberCount($uid = 0)
    {
        if ($uid) {

            $where = "`pid` = " . $uid . " AND `stat`=1";
        } else {

            $where = "`pid` = " . $this->_user['uid'] . " AND `stat`=1";
        }
        $sql = "SELECT count(`uid`) FROM {$this->_prefix['primary']}member_account WHERE " . $where;
        return $this->db->getone($sql);
    }
    //查看是否有付款注册会员并且已发货
    public function getShippingStatus()
    {
        $sql = "SELECT count(*) FROM {$this->_prefix['primary']}member_payinfo WHERE `uid`=" . $this->_user['uid'] . " AND `pay_status`=2 AND `shipping_status`>0";
        $num = $this->db->getone($sql);
        return $num;
    }

    public function getMemberOpenShippingDetail()
    {

        $sql  = "SELECT  * FROM {$this->_prefix['primary']}member_payinfo WHERE `uid`=" . $this->_user['uid'] . " AND `pay_status`=2 AND `shipping_status`>0";
        $data = $this->sql($sql);

        if ($data) {

            foreach ($data as $key => $val) {

                if ($val['tao_province_id'] > 0) {
                    $region_ids[] = $val['tao_province_id'];
                }

                if ($val['tao_city_id'] > 0) {
                    $region_ids[] = $val['tao_city_id'];
                }

                if ($val['tao_county_id'] > 0) {
                    $region_ids[] = $val['tao_county_id'];
                }

                if ($val['shipping_status'] == 1) {
                    $data[$key]['shipping_status'] = "已发货";

                } else if ($val['shipping_status'] == 2) {
                    $data[$key]['shipping_status'] = "已收货";
                } else {
                    $data[$key]['shipping_status'] = "未发货";
                }
            }
            if ($region_ids) {
                $region = $this->getRegionWithId($region_ids);
            }
        }

        return array(
            'data'   => $data,
            'region' => $region,
        );

    }

    //开通会员后确认收货
    public function reveiveOrder($order_id)
    {
        $order_id    = intval($order_id);
        $arr         = array();
        $arr['code'] = 900;
        $arr['msg']  = "确认收货失败，请重试";
        if ($order_id) {
            $sql = "UPDATE {$this->_prefix['primary']}member_payinfo SET `shipping_status`=2,`receive_time`=" . time() . " WHERE `order_id`=" . $order_id . " AND `uid`=" . $this->_user['uid'] . " AND `pay_status`=2";
            $rs  = $this->sql($sql);
            if ($rs > 0) {
                $arr['code'] = 200;
                $arr['msg']  = "确认收货成功!";
            } else {
                $arr['code'] = 902;

            }

        } else {
            $arr['code'] = 901;
        }

        return $arr;
    }

    public function affiche($level_type)
    {

        $sql  = "SELECT `article_id`,`title`,`update_time` FROM {$this->_prefix['primary']}article WHERE `is_open`=1 AND `caid`=1 ORDER BY `article_id` DESC";
        $data = $this->sql($sql);
        if ($data) {
            return $data;
        }
    }
    //统计
    public function getCountyAgencyStatistics($pid = 0, $team_num = 0, $team_money = 0)
    {

        if (empty($pid)) {

            $where = " AND `pid`=" . $this->_user['uid'];
        } else {

            $where = " AND `pid` IN (" . $pid . ")";
        }

        $sql     = "SELECT `uid`,`pid`,`member_level` FROM {$this->_prefix['primary']}member_account WHERE  `stat`=1 " . $where;
        $members = $this->sql($sql);
        // print_r($members);die;
        //直推加盟仓人数
        $direct_num = count($members);
        //团队加盟仓直推人数
        // $team_num = 0;

        //团队累计金额
        //$team_money = 0;

        $pids = ''; //所以的直推uid
        if (!empty($members)) {

            //$direct_total_num   += $direct_num;
            foreach ($members as $val) {
                if ($val['member_level'] == 3) {

                    $team_num += 1;
                }

                if ($val['uid'] > 0) {

                    $pids .= empty($pids) ? $val['uid'] : ',' . $val['uid'];
                }
            }

            $pidss = trim($pids);

            if (!empty($pidss)) {
                $sql       = "SELECT `uid`,`level_money`,`money` FROM {$this->_prefix['primary']}member_payinfo WHERE  `uid` IN (" . $pidss . ") AND `pay_status`=2";
                $memberPay = $this->sql($sql);

                if ($memberPay) {
                    foreach ($memberPay as $v) {
                        $team_money += $v['level_money'];

                    }

                }

                return $this->getCountyAgencyStatistics($pidss, $team_num, $team_money);

            }

        }

        $sql      = "SELECT  `level_money` FROM {$this->_prefix['primary']}member_payinfo WHERE  `uid`=" . $this->_user['uid'] . " AND `pay_status`=2";
        $my_money = $this->db->getone($sql);

        $arr               = array();
        $arr['team_num']   = $team_num;
        $arr['team_money'] = $team_money + $my_money;

        return $arr;

    }

    public function getMyDirectNum()
    {

        $sql           = "SELECT COUNT(*) FROM {$this->_prefix['primary']}member_account WHERE  `stat`=1 AND `member_level`=3 AND `pid`=" . $this->_user['uid'];
        $my_direct_num = $this->db->getone($sql);
        $sql           = "SELECT COUNT(*) FROM {$this->_prefix['primary']}member_account WHERE  `stat`=1 AND `member_level`=3 AND `uid`=" . $this->_user['uid'];
        $num           = $this->db->getone($sql);
        if ($num > 0) {

            $my_direct_num += 1;
        }
        return $my_direct_num;
    }

    //修改用户等级
    public function saveMemberLevel($level)
    {
        if ($level > 0) {
            $sql          = "SELECT `member_level` FROM {$this->_prefix['primary']}member_account WHERE `uid`=" . $this->_user['uid'];
            $member_level = $this->db->getone($sql);
            if ($member_level != $level) {
                $sql = "UPDATE {$this->_prefix['primary']}member_account SET `member_level`=" . $level . " WHERE `uid`=" . $this->_user['uid'];
                $rs  = $this->sql($sql);

            }

        }

    }
    // 获取设置
    public function getSetting()
    {
        $sql     = "SELECT `setting` FROM {$this->_prefix['primary']}setting ORDER BY `setting_id` DESC LIMIT 1";
        $setting = $this->db->getone($sql);
        if ($setting != "") {
            return json_decode($setting, true);
        }

    }

}
